package com.supor.aiot.common.app.api;

import com.android.baseconfig.base.BaseRetrofit;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.android.baseconfig.data.http.okhttp.listener.DownloadProgressListener;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: DownloadImpl <br>
 * 作者: lei <br>
 * 日期: 2021/1/11 <br>
 */
public class DownloadImpl extends BaseRetrofit<DownloadService> implements DownloadService {
    private static DownloadImpl instance;

    public static DownloadImpl getInstance() {
        if (instance == null) {
            instance = new DownloadImpl();
        }
        return instance;
    }

    public void download(String url, String filePath, DownloadProgressListener listener) {
        File file = new File(filePath);
        if (!file.exists()) {
            listener.onFailed(new Throwable(filePath + " file not found"));
            return;
        }
        download(url, file, listener);
    }

    public void download(String url, File file, DownloadProgressListener listener) {
        Call<ResponseBody> call = api.download(url);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                ThreadUtils.execute(() -> {
                    if (response.isSuccessful()) {
                        if (listener != null) {
                            listener.onStart();
                        }
                        try {
                            long total = response.body().contentLength();//需要下载的总大小
                            long current = 0;
                            int report = 0;
                            InputStream inputStream = response.body().byteStream();
                            BufferedInputStream bis = new BufferedInputStream(inputStream);
                            FileOutputStream fileOutputStream = new FileOutputStream(file);
                            byte[] bytes = new byte[4096];
                            int len = 0;
                            while ((len = bis.read(bytes)) != -1) {
                                fileOutputStream.write(bytes, 0, len);
                                fileOutputStream.flush();
                                current = current + len;
                                if (listener != null && (report % 20 == 0)) {
                                    listener.update(current, total, false);
                                }
                                report++;
                                // Logc.i("current=" + current + ", total=" + total + "----" + (current / (total*1.0)) * 100 + "%");
                            }
                            fileOutputStream.flush();
                            fileOutputStream.close();
                            bis.close();
                            inputStream.close();
                            if (listener != null) {
                                listener.onComplete(file.getAbsolutePath());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            if (listener != null) {
                                listener.onFailed(e);
                            }
                        }
                    } else {
                        Logc.d("server contact failed");
                        if (listener != null) {
                            listener.onFailed(new Throwable("server contact failed"));
                        }
                    }
                });

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (listener != null) {
                    listener.onFailed(t);
                }
            }
        });
    }

    @Override
    public Call<ResponseBody> download(String url) {
        return api.download(url);
    }
}
